'use client';

import Editor, { Monaco, OnMount } from '@monaco-editor/react';
import { useState, useRef } from 'react';

interface CodeEditorProps {
  initialValue?: string;
  onChange(value: string): void;
}

export default function CodeEditor({ 
  initialValue = '<!DOCTYPE html>\n<html>\n</html>', 
  onChange 
}: CodeEditorProps) {
  const [error, setError] = useState('');
  const editorRef = useRef<any>(null);

  // 编辑器初始化完成回调
  const handleEditorDidMount: OnMount = (editor, monaco) => {
    editorRef.current = editor;
    
    // 配置自动完成
    monaco.languages.html.htmlDefaults.setOptions({
      suggest: { html5: true },
      format: {
          extraLiners: '',
          wrapAttributes: 'auto',
          indentInnerHtml: true,
          wrapLineLength: 80,
          tabSize: 2,
          insertSpaces: true,
          unformatted: 'span',
          contentUnformatted: 'pre',
          preserveNewLines: true,
          maxPreserveNewLines: 10,
          indentHandlebars: true,
          endWithNewline: true,
      }
    });
  };

  // // 格式化代码
  // const formatCode = async () => {
  //   try {
  //     const raw = editorRef.current.getValue();
  //     const formatted = await prettier.format(raw, {
  //       parser: 'html',
  //       plugins: [parserHtml],
  //       htmlWhitespaceSensitivity: 'ignore'
  //     });
  //     onChange(formatted);
  //   } catch (err) {
  //     setError('格式错误: ' + (err as Error).message);
  //   }
  // };

  return (
    <div className="h-full relative">
      <div className="absolute right-4 top-2 z-10 flex gap-2">
        {/* <button
          // onClick={formatCode}
          className="px-3 py-1 bg-blue-600 text-white rounded hover:bg-blue-700 text-sm"
        >
          格式化
        </button> */}
        
      </div>
      
      <Editor
        height="100%"
        defaultLanguage="html"
        defaultValue={initialValue}
        onChange={(value: any) => onChange(value || '')}
        theme="vs-dark"
        onMount={handleEditorDidMount}
        options={{
          minimap: { enabled: false },
          fontSize: 14,
          lineNumbers: 'on',
          roundedSelection: false,
          scrollBeyondLastLine: false,
          automaticLayout: true,
          tabSize: 2,
          insertSpaces: true,
          autoClosingQuotes: 'always',
          formatOnPaste: true,
          formatOnType: true,
        }}
      />

      {error && (
        <div className="absolute bottom-2 left-2 bg-red-100 text-red-700 p-2 rounded text-sm">
          {error}
        </div>
      )}
    </div>
  );
}
